package mybatis.plugins.annotations;

import mybatis.exception.MyBatisException;
import mybatis.plugins.MapperFactoryBean;
import mybatis.session.SqlSessionFactory;
import spring.annotations.ImportBeanDefinitionRegistrar;
import spring.annotations.Query;
import utils.ReflectUtils;

import java.util.Objects;

public class MapperFactoryRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public Object registerBeanDefinitions(Object... args) {
        if (args.length != 2) {
            throw new MyBatisException("当前未提供需要注册的DAO接口");
        }
        Query factoryQuery = (Query) args[0];
        SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) factoryQuery
                .query(ReflectUtils.convertName(SqlSessionFactory.class.getSimpleName()));
        if (Objects.isNull(sqlSessionFactory)) {
            throw new MyBatisException("无法获取到有效的 sqlSessionFactory 对象");
        }
        String mapperInterface = (String) args[1];
        MapperFactoryBean<?> factoryBean = new MapperFactoryBean<>();
        factoryBean.setSqlSessionFactory(sqlSessionFactory);
        factoryBean.setMapperInterface(mapperInterface);
        return factoryBean;
    }


}
